package com.zgt.dao.impl;

import java.util.Iterator;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.zgt.dao.AdminDao;
import com.zgt.model.Admin;
import com.zgt.model.Setting;

@Repository("adminDao")
public class AdminDaoImpl implements AdminDao {

	private HibernateTemplate hibernateTemplate;

	public HibernateTemplate getHibernateTemplate() {
		return hibernateTemplate;
	}

	@Resource
	public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
		this.hibernateTemplate = hibernateTemplate;
	}

	public void changePassword(Admin admin) {
		hibernateTemplate.saveOrUpdate(admin);
	}

	@SuppressWarnings("unchecked")
	public Admin checkLogin(Admin admin) {
		Admin a = null;
		List<Admin> admins = hibernateTemplate.findByExample(admin);
		Iterator<Admin> iadmins = admins.iterator();
		while (iadmins.hasNext()) {
			a = iadmins.next();
		}
		// 返回持久化的对象
		return a;
	}

	public void deleteAdminByid(int id) {
		Admin admin = new Admin();
		admin.setId(id);
		hibernateTemplate.delete(admin);
	}

	@Transactional
	public boolean saveAdmin(Admin admin) {
		boolean success = false;
		if (isExist(admin)) {
			hibernateTemplate.save(admin);
			success = true;
		}
		return success;
	}

	@SuppressWarnings("unchecked")
	public boolean isExist(Admin admin) {
		boolean noExist = true;
		List<Admin> admins = hibernateTemplate.find(
				"from Admin a where a.username=?", admin.getUsername());
		Iterator<Admin> iadmins = admins.iterator();
		if (iadmins.hasNext()) {
			noExist = false;
		}
		return noExist;
	}

	@SuppressWarnings("unchecked")
	public List<Admin> admins(int pageStart,int pageSize) {
		List<Admin> admins = hibernateTemplate.findByCriteria(DetachedCriteria.forClass(Admin.class), pageStart, pageSize);
		return admins;
	}

	public Admin getAdminByid(int id) {
		Admin admin = new Admin();
		List<Admin> admins=hibernateTemplate.findByCriteria(DetachedCriteria.forClass(Admin.class).add(Restrictions.eq("id", id)));
		Iterator<Admin> iadmins = admins.iterator();
		while (iadmins.hasNext()) {
			admin = iadmins.next();
		}
		return admin;
	}

	public int getCount() {
		List<Admin> admins = hibernateTemplate.find("from Admin");
		return admins.size();
	}

}
